package ras;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/ws/{mid}")
public class WebSocketServer {

    private static Map<String, WebSocketServer> sessions = new ConcurrentHashMap<>();
    private static Map<String, String> streamPairs = new ConcurrentHashMap<>();
    private Session session;
    private String mid;

    private static final int OFFLINE = 0;

    private static final int ONLINE = 1;

//    private static final int BUSY = 2;

    private UserDao userDao;


    @OnOpen
    public void onOpen(@PathParam("mid") String mid, Session session) {
        this.mid = mid;
        this.session = session;
        sessions.put(mid, this);
        userDao = new UserDao();
        if (userDao.setUserStatus(mid, ONLINE)) {
            System.out.println(mid + "上线");
        }
    }

    @OnClose
    public void onClose() {
        sessions.remove(mid);
        if (userDao.setUserStatus(mid, OFFLINE)) {
            System.out.println(mid + "下线");
        }
    }

    @OnMessage
    public void onMessage(@PathParam("mid") String mid, String message) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            MessagePacket packet = mapper.readValue(message, MessagePacket.class);
            String msg = null;
            System.out.println(mid + "发送Message给" + packet.getSid());
            System.out.println("Message:"+message);
            if (packet.getMsg().equals("online")) {
                packet.setList(userDao.getOnlineUserList());
            }
            if (packet.getMsg().equals("accept")) {
                streamPairs.put(packet.getSid()+"-stream", packet.getMid()+"-stream");
                System.out.println("建立通信对：" + packet.getSid()+"-stream:" + streamPairs.get(packet.getSid()+"-stream"));
            }
            msg = mapper.writeValueAsString(packet);
            sendMessageToClient(packet.getSid(), msg);
            System.out.println(mid + "发送Message完成");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnMessage(maxMessageSize = 1000000)
    public void onStream(@PathParam("mid") String mid, ByteBuffer byteBuffer) {
        System.out.println(mid + "发送Stream给" + streamPairs.get(mid));
        try {
            sendBinaryToClient(streamPairs.get(mid), byteBuffer);
            System.out.println(mid + "发送Stream完成");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnError
    public void onError(@PathParam("mid") String mid, Throwable t) {
        System.out.println(mid + "连接异常");
        t.printStackTrace();
    }

    public void sendMessage(String message) throws IOException {
            this.session.getBasicRemote().sendText(message);
    }

    public void sendMessageToClient(String id, String message) throws IOException {
        if (sessions.get(id) != null) {
            sessions.get(id).sendMessage(message);
        }
    }

    public void sendBinary(ByteBuffer byteBuffer) throws IOException {
        this.session.getBasicRemote().sendBinary(byteBuffer);
    }

    public void sendBinaryToClient(String id, ByteBuffer byteBuffer) throws IOException {
        if (sessions.get(id) != null) {
            sessions.get(id).sendBinary(byteBuffer);
        }
    }
}

